﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Mapster;

using OfficialWeb.Application;

using OOS.Application.Category.Services.Interfaces;
using OOS.Application.Dish.Dtos;
using OOS.Application.Dish.Services.Interfaces;
using OOS.Application.User.Services.Interfaces;
using OOS.Core.Category;
using OOS.Core.Dish;
using OOS.Core.RelyOn;

namespace OOS.Application.Dish.Services
{
    /// <summary>
    /// 菜品管理
    /// </summary>
    public class DishBasicService : IDishBasicService, ITransient
    {
        private readonly ISqlSugarClient _client;
        private readonly IDishFlavorService _flavorService;
        private readonly IUserBasicService _userBasicService;
        private readonly ICategoryBasicService _categoryBasicService;

        public DishBasicService(ISqlSugarClient client, IDishFlavorService flavorService, IUserBasicService userBasicService, ICategoryBasicService categoryBasicService)
        {
            _client = client;
            _flavorService = flavorService;
            _userBasicService = userBasicService;
            _categoryBasicService = categoryBasicService;
        }

        /// <summary>
        /// 新增菜品
        /// </summary>
        /// <param name="dishBasic"></param>
        /// <returns></returns>
        public bool InsertDishBasic(DishBasic dishBasic)
        {
            if (dishBasic == null) return false;
            //判断token中是否有用户数据
            int userId = JWTToken.GetUser().Id;
            if (userId <= 0) { return false; }
            dishBasic.CreateUser = userId;
            dishBasic.CreateDate = DateTime.Now;
            dishBasic.UpdateUser = userId;
            dishBasic.UpdateDate = DateTime.Now;
            dishBasic.Status = 1;
            //插入菜品基本数据并返回菜品id
            int dishId = _client.Insertable(dishBasic).ExecuteReturnIdentity();
            //插入菜品口味
            if (dishBasic.dishFlavors != null)
            {
                dishBasic.dishFlavors.ForEach(dishFlavor =>
                {
                    _flavorService.InsertDishFlavor(dishFlavor, dishId);
                });
            }
            return dishId > 0;
        }

        /// <summary>
        /// 根据id获取菜品详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DishBasicDto SelectDishById(int id)
        {
            if (id <= 0) return new DishBasicDto();
            DishBasic dishBasic = SelectDishBasicById(id);
            if (dishBasic == null) return new DishBasicDto();
            int createId = dishBasic.CreateUser;
            int updateId = dishBasic.UpdateUser;
            DishBasicDto dto = dishBasic.Adapt<DishBasicDto>();
            dto.CreateUser = _userBasicService.SelectUserById(createId).Username;
            dto.UpdateUser = _userBasicService.SelectUserById(updateId).Username;
            dto.dishFlavors = _flavorService.SelectFlavorListByDishId(id);
            return dto;
        }

        /// <summary>
        /// 根据条件(菜品名称模糊查询，菜品状态精确查询，菜品分类精确查询)查询菜品列表
        /// </summary>
        /// <param name="dishBasic"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public PageResponseDto<List<DishBasicDto>> SelectPageByConditions(DishBasic dishBasic, int pageIndex, int pageSize)
        {
            int size = 0;
            List<DishBasicDto> dishBasicDtos = _client.Queryable<DishBasic>()
                .Where(db => db.IsDeleted == false)
                .WhereIF(!String.IsNullOrEmpty(dishBasic.DishName), db => db.DishName.Contains(dishBasic.DishName))
                .WhereIF(dishBasic.Status != 0, db => db.Status == dishBasic.Status)
                .WhereIF(dishBasic.CategoryId != 0, db => db.CategoryId == dishBasic.CategoryId)
                .OrderBy(db => db.Sort,OrderByType.Desc)
                .OrderBy(db => db.CreateDate,OrderByType.Desc)
                .ToPageList(pageIndex, pageSize, ref size)
                .Adapt<List<DishBasicDto>>();
            for(int i=0; i< dishBasicDtos.Count; i++)
            {
                dishBasicDtos[i] = SelectDishById(dishBasicDtos[i].Id);
            }
            PageResponseDto<List<DishBasicDto>> pageResponseDto = new PageResponseDto<List<DishBasicDto>>();
            pageResponseDto.data = dishBasicDtos;
            pageResponseDto.size = size;
            return pageResponseDto;
        }

        /// <summary>
        /// 根据id修改菜品信息
        /// </summary>
        /// <param name="dishBasic"></param>
        /// <returns></returns>
        public bool UpdateDishBasicById(DishBasic dishBasic)
        {
            if (dishBasic == null) return false;
            DishBasic dish = SelectDishBasicById(dishBasic.Id);
            if(dish == null) return false;
            //判断token中是否有用户数据
            int userId = 1; //JWTToken.GetUser().Id;
            //if (userId <= 0) { return false; }
            dishBasic.CreateUser = dish.CreateUser;
            dishBasic.CreateDate = dish.CreateDate;
            dishBasic.UpdateUser = userId;
            dishBasic.UpdateDate = DateTime.Now;
            //清空菜品口味
            _flavorService.DeleteFlavorListByDishId(dishBasic.Id);
            //添加菜品口味
            if (dishBasic.dishFlavors != null)
            {
                dishBasic.dishFlavors.ForEach(flavor =>
                {
                    _flavorService.InsertDishFlavor(flavor, dish.Id);
                });
            }
            return _client.Updateable(dishBasic).ExecuteCommand() > 0;

        }

        /// <summary>
        /// 根据id删除菜品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteDishBasicById(int id)
        {
            if(id <= 0) return false;
            DishBasic dishBasic = SelectDishBasicById(id);
            dishBasic.IsDeleted = true;
            Boolean flag =  _flavorService.DeleteFlavorListByDishId(dishBasic.Id);
            if (!flag) return false;
            return UpdateDishBasicById(dishBasic);
        }

        /// <summary>
        /// 根据id修改菜品状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool UpdateStatusById(int id)
        {
            if (id <= 0) return false;
            int userId = JWTToken.GetUser().Id;
            if (userId <= 0) { return false; }
            DishBasic dishBasic = SelectDishBasicById(id);
            dishBasic.Status = dishBasic.Status == 1 ? 2 : 1;
            dishBasic.UpdateUser = userId;
            dishBasic.UpdateDate = DateTime.Now;
            return _client.Updateable(dishBasic).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 批量修改菜品状态
        /// </summary>
        /// <param name="dishSelection"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public bool UpdateStatusByIds(int[] dishSelection, int type)
        {
            if (dishSelection == null || dishSelection.Length <= 0) return false;
            int userId = JWTToken.GetUser().Id;
            if (userId <= 0) { return false; }
            foreach (int id in dishSelection)
            {
                DishBasic dishBasic = SelectDishBasicById(id);
                dishBasic.Status = type;
                dishBasic.UpdateUser = userId;
                dishBasic.UpdateDate = DateTime.Now;
                Boolean flag = _client.Updateable(dishBasic).ExecuteCommand() > 0;
                if (!flag) return false;
            }
            return true;
        }

        /// <summary>
        /// 批量删除菜品
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DeleteDishBasicByIds(int[] ids)
        {
            if (ids == null || ids.Length <= 0) return false;
            foreach (int id in ids)
            {
                Boolean flag = this.DeleteDishBasicById(id);
                if (!flag) return false;
            }
            return true;
        }

        /// <summary>
        /// 根据id获取菜品详情数据库原始数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private DishBasic SelectDishBasicById(int id)
        {
            return _client.Queryable<DishBasic>()
                .Where(db => db.Id == id)
                .Where(db => db.IsDeleted == false)
                .Single();
        }

        /// <summary>
        /// 获取不同分类下菜品数据
        /// </summary>
        /// <returns></returns>
        public List<DishByCategory> SelectDishListByCategory()
        {
            CategoryBasic categoryBasic = new CategoryBasic();
            categoryBasic.Type = 1;
            var categoryList =  _categoryBasicService.SelectPageByConditions(categoryBasic, 1, 100).data;
            List<DishByCategory> dishByCategories = new List<DishByCategory>();
            DishByCategory dishCategory = null;
            DishBasic dishBasic = null;
            foreach ( var category in categoryList)
            {
                dishCategory = category.Adapt<DishByCategory>();
                dishBasic = new DishBasic();
                dishBasic.CategoryId = category.Id;
                var dishList =  this.SelectPageByConditions(dishBasic, 1, 1000).data;
                dishCategory.dishList = dishList;
                dishByCategories.Add(dishCategory);
            }
            return dishByCategories;
        }
    }
}
